package com.sgb.kjwl.view.ui.activity.self;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddCarNextBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.widget.ChoosePictureDialog;
import com.sgb.kjwl.viewmodel.self.AddCarInfoNextModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 车辆添加提交页
 */
public class AddCarInfoNextActivity extends AppActivity {
    ActivityAddCarNextBinding binding;
    public static final int CAR_PIC = 1;//车辆证
    public static final int TRANSPORT_LICENS = 2;  //运输证
    public static final int TRANSPORT_LICENS_ATTACHED = 3;//附页
    private ChoosePictureDialog mChoosePictureDialog;
    int type;
    boolean isHaveTransport=false;//是否填上传运输证
    @Inject
    AddCarInfoNextModel viewModel;
    private String carPic, transportPic, transporPic2;
    List<File> files=new ArrayList<>();
    File carFile,transportFile1,transportFile2;
    private boolean isChange;


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_add_car_next);
//        APIManager.getInstance().changeAPIManager(BuildConfig.LOCAL_TEST_URL_ZHANG);
        binding.include.titleView.setText("新增车辆");
        binding.include.ivBack.setOnClickListener(this);
        binding.setOnClick(this);
        CarInfoEntity entity= (CarInfoEntity) getIntent().getSerializableExtra("data");
        isChange=getIntent().getBooleanExtra("isChange",true);
        if(entity!=null) {
            RequestOptions options = new RequestOptions().placeholder(R.drawable.null_img_list).error(R.drawable.null_img_list);

                if(!TextUtils.isEmpty(entity.getTransportCertificateMain())){
                    transportPic=entity.getTransportCertificateMain();
                    Glide.with(getActivity()).load(entity.getTransportCertificateMain()).apply(options).into(binding.ivCertificates);
                }else{
                    entity.setTransportCertificateMain("");
                }
                if(!TextUtils.isEmpty(entity.getTransportCertificateVice())){
                    transporPic2=entity.getTransportCertificateVice();
                    Glide.with(getActivity()).load(entity.getTransportCertificateVice()).apply(options).into(binding.ivCertificates2);
                }else{
                    entity.setTransportCertificateVice("");
                }
                if(!TextUtils.isEmpty(entity.getTransportCertificateNum())){
                    binding.tvTransportNo.setText(entity.getTransportCertificateNum());
                }else{
                    entity.setTransportCertificateNum("");
                }


            if(!TextUtils.isEmpty(entity.getCarImage())){
                carPic=entity.getCarImage();
                Glide.with(getActivity()).load(entity.getCarImage()).into(binding.ivCar);
            }
            viewModel.carInfoEntity.set(entity);
        }
  /*      String fileStr=getIntent().getStringExtra("vehiclelicense");
        String fileStr2=getIntent().getStringExtra("vehiclelicense2");
        if(!TextUtils.isEmpty(fileStr)){
            File file=new File(fileStr);
            files.add(file);
        }
        if(!TextUtils.isEmpty(fileStr2)){
            File file=new File(fileStr2);
            files.add(file);
        }
*/
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                String transNo=binding.tvTransportNo.getText().toString();
                if(!TextUtils.isEmpty(transNo)){
                    viewModel.carInfoEntity.get().setTransportCertificateNum(transNo);
                }
                EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_CARINFO).setMessageData(viewModel.carInfoEntity.get()));
                finish();
                break;
            case R.id.ll_add_car:
                showPictureDailog(R.drawable.img_sl_car, CAR_PIC);
                break;
            case R.id.iv_certificates:
                showPictureDailog(R.drawable.img_sl_dluzy, TRANSPORT_LICENS);
                break;
            case R.id.iv_certificates2:
                showPictureDailog(R.drawable.img_sl_dlfy, TRANSPORT_LICENS_ATTACHED);
                break;
            case R.id.complete_view:
                if(TextUtils.isEmpty(carPic)&&carFile==null){
                    MToast.showToast(getActivity(),"请上传车辆照片");
                    return;
                }
                String transportNo=binding.tvTransportNo.getText().toString();

           /*         if(TextUtils.isEmpty(transportPic)&&transportFile1==null){
                        MToast.showToast(getActivity(),"请上传道路运输证主页照片");
                        return;
                    }
                    if(TextUtils.isEmpty(transporPic2)&&transportFile2==null){
                        MToast.showToast(getActivity(),"请上传道路运输证副页照片");
                        return;
                    }
                    if(TextUtils.isEmpty(transportNo)){
                        MToast.showToast(getActivity(),"请输入道路运输证编号");
                        return;
                    }*/
                    if(!TextUtils.isEmpty(transportNo)){
                        if(transportNo.length()<12) {
                            MToast.showToast(getActivity(), "请输入道路运输证12位编号");
                            return;
                        }else{
                            viewModel.carInfoEntity.get().setTransportCertificateNum(transportNo);
                        }
                    }


//                viewModel.authCar(this,isChange);

                break;
        }
    }

    private void showPictureDailog(int pic, int type) {
        mChoosePictureDialog = new ChoosePictureDialog(getActivity(), pic);
        mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
            @Override
            public void onItemClick(String ids) {
                if (ids.equals("拍照")) {
                    getTackPhoto(type);
                } else if (ids.equals("从手机相册选择")) {
                    getCerImage(type);
                }

            }
        });
        mChoosePictureDialog.show(getSupportFragmentManager(), "1");
    }

    private void getCerImage(int type) {
        this.type = type;
        MLog.d("type == ", "" + type);
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(1)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void getTackPhoto(int type) {
        this.type = type;
        MLog.d("type == ", "" + type);
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .compress(true)//是否压缩
                .minimumCompressSize(10240)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    MLog.d("type ", type + "");
                    if (type == CAR_PIC) {

                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        File file = new File(selectList.get(0).getRealPath());
                        MLog.d("图片路径：", selectList.get(0).getRealPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }

                        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.ivCar);
                      /*  carFile=file;
                        files.add(file);*/
                        viewModel.uploadMutiFileModel(this,file, CAR_PIC);

                    } else if (type == TRANSPORT_LICENS) {

                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        File file = new File(selectList.get(0).getRealPath());
                        MLog.d("图片路径：", selectList.get(0).getRealPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }


                        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.ivCertificates);
                       /* transportFile1=file;
                        files.add(file);*/
                        viewModel.uploadMutiFileModel(this,file, TRANSPORT_LICENS);
                    }else if(type == TRANSPORT_LICENS_ATTACHED){
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        File file = new File(selectList.get(0).getRealPath());
                        MLog.d("图片路径：", selectList.get(0).getRealPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }


                        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.ivCertificates2);
                      /*  transportFile2=file;
                        files.add(file);*/
                        viewModel.uploadMutiFileModel(this,file, TRANSPORT_LICENS_ATTACHED);
                    }

            }
        }
    }

    public void uploadImgSuccess(String toString, int type) {
        switch (type) {
            case CAR_PIC:
                carPic = toString;
                viewModel.carInfoEntity.get().setCarImage(carPic);
                break;
            case TRANSPORT_LICENS:
                transportPic=toString;
                viewModel.carInfoEntity.get().setTransportCertificateMain(transportPic);
                break;
            case TRANSPORT_LICENS_ATTACHED:
                transporPic2=toString;
                viewModel.carInfoEntity.get().setTransportCertificateVice(transporPic2);
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        APIManager.getInstance().changeAPIManager(BuildConfig.LOCAL_TEST_URL);
    }

}
